package com.cnswhy.cloud.server.comsumer.receiver;


import com.cnswhy.cloud.common.core.exception.BizException;
import com.cnswhy.cloud.common.logging.constant.MDCConstant;
import com.cnswhy.cloud.server.common.entity.constant.AmqpExchange;
import com.cnswhy.cloud.server.common.entity.mq.CpsOrderQueryMQ;
import com.cnswhy.cloud.server.common.entity.mq.OrderQueryMQ;
import com.cnswhy.cloud.server.comsumer.event.CpsOrderQueryEvent;
import com.cnswhy.cloud.server.comsumer.event.OrderQueryMqEvent;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.MDC;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Slf4j
public class CpsOrderQueryMessageReceiver {

    @Autowired(required = false)
    private List<CpsOrderQueryEvent> events;

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = AmqpExchange.CPS_ORDER_QUERY_MESSAGE + AmqpExchange.QUEUE),
            exchange = @Exchange(value = AmqpExchange.CPS_ORDER_QUERY_MESSAGE, type = ExchangeTypes.FANOUT)
    ))
    public void verify(CpsOrderQueryMQ cpsOrderQueryMQ) {
        if (StringUtils.isNotBlank(cpsOrderQueryMQ.getTraceId())) {
            MDC.put(MDCConstant.LOG_TRACE_ID, cpsOrderQueryMQ.getTraceId());
        }

        if (events != null) {
            for (CpsOrderQueryEvent event : events) {
                try {
                    event.query(cpsOrderQueryMQ);
                } catch (BizException e) {
                    log.error("查询异常:{}", e.getMessage());
                }catch (Exception e){
                    e.printStackTrace();
                    log.error("消费队列异常");
                }
            }
        }
    }
}
